package org.android;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class AddTripView extends Activity {
	private EditText departure;
	private EditText arrival;
	private TextView dateTxv;
	private TextView dayTxv;
	private TextView timeTxv;
	private Button confirm;
	private Button dayBtn;
	private Button dateBtn;
	private Button timeBtn;
	private RadioButton driver;
	private ArrayList<String> dayList;
	private HashMap<String, Boolean> selectedDayList;

	private List<HelloRoadAddress> addressDepartureResult;
	private List<HelloRoadAddress> addressArrivalResult;


	private HelloRoadAddress coord;
	private Boolean departProposal = false;
	
	private static final int ACTIVITY_CREATE = 0;
	private static final int DATE_DIALOG_ID = 1;
	private static final int DAY_DIALOG_ID = 2;
	private static final int TIME_DIALOG_ID = 3;
	private static final int ADDRESS_DEPARTURE_DIALOG_ID = 4;
	private static final int ADDRESS_ARRIVAL_DIALOG_ID = 5;

	
	private int mYear;
	private int mMonth;
	private int mDay;
	
	private int mHour;
	private int mMinute;

	private int userId;

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;
			updateDateDisplay();
		}
	};

	private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {

		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			mHour = hourOfDay;
			mMinute = minute;
			updateTimeDisplay();
		}
	};

	public int getUserId() {
		return userId;
	}

	public void setUserId(int userId) {
		this.userId = userId;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.trip_edit);
		
		Bundle extras = getIntent().getExtras();
		userId = extras.getInt("userId");

		departure = (EditText) findViewById(R.id.departureEdit);
		arrival = (EditText) findViewById(R.id.arrivalEdit);
		confirm = (Button) findViewById(R.id.tripConfirm);
		dateTxv = (TextView) findViewById(R.id.dateDisplay);
		dayTxv = (TextView) findViewById(R.id.dayDisplay);
		timeTxv = (TextView) findViewById(R.id.timeDisplay);
		dayBtn = (Button) findViewById(R.id.dayChooser);
		dateBtn = (Button) findViewById(R.id.dateChooser);
		timeBtn = (Button) findViewById(R.id.timeChooser);
		driver = (RadioButton) findViewById(R.id.driverBox);

		addressDepartureResult = new ArrayList<HelloRoadAddress>();
		addressArrivalResult = new ArrayList<HelloRoadAddress>();
		
		selectedDayList = new HashMap<String, Boolean>();
		selectedDayList.put("monday", false);
		selectedDayList.put("tuesday", false);
		selectedDayList.put("wednesday", false);
		selectedDayList.put("thursday", false);
		selectedDayList.put("friday", false);
		selectedDayList.put("saturday", false);
		selectedDayList.put("sunday", false);
		
		dayList = new ArrayList<String>();
		dayList.add("monday");
		dayList.add("tuesday");
		dayList.add("wednesday");
		dayList.add("thursday");
		dayList.add("friday");
		dayList.add("saturday");
		dayList.add("sunday");

		final Geocoder geocoder = new Geocoder(this, Locale.getDefault());

		
		// get the current date
		final Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);
		mHour = c.get(Calendar.HOUR_OF_DAY);
		mMinute = c.get(Calendar.MINUTE);
		
		dateBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showDialog(DATE_DIALOG_ID);
			}
		});
		
		dayBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showDialog(DAY_DIALOG_ID);
			}
		});
		
		timeBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				showDialog(TIME_DIALOG_ID);
			}
		});

		confirm.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// sauvegarde des infos ou creation du nouveau trajet.
				String from = departure.getText().toString();
				String to = arrival.getText().toString();
				String time = timeTxv.getText().toString();
				String date = dateTxv.getText().toString();
				String days = dayTxv.getText().toString();

				if (from.equals("")) {
					Toast.makeText(getBaseContext(), "Give the departure",
							Toast.LENGTH_SHORT).show();
				} else if (to.equals("")) {
					Toast.makeText(getBaseContext(), "Give the destination",
							Toast.LENGTH_SHORT).show();
				} else if (date.equals("") && days.equals("")) {
					Toast.makeText(getBaseContext(),
							"Choose a date or a frequency for the trip",
							Toast.LENGTH_SHORT).show();
				} else if (time.equals("")) {
					Toast.makeText(getBaseContext(),
							"Give the time of the trip", Toast.LENGTH_SHORT)
							.show();
				} else {
					try {
						List<Address> tmp = geocoder.getFromLocationName(from,
								5);
						if (tmp.size() > 1) {
							for (Address address : tmp) {
								addressDepartureResult
										.add(new HelloRoadAddress(address));
							}
							departProposal = true;
							showDialog(ADDRESS_DEPARTURE_DIALOG_ID);
							return;
						} else {
							coord = new HelloRoadAddress(tmp.get(0));
						}
					} catch (IOException e) {
						e.printStackTrace();
					}

					try {
						List<Address> tmp = geocoder.getFromLocationName(to,
								5);
						if (tmp.size() > 1) {
							for (Address address : tmp) {
								addressArrivalResult.add(new HelloRoadAddress(address));
							}
							showDialog(ADDRESS_ARRIVAL_DIALOG_ID);
							return;
						} else {
							coord = new HelloRoadAddress(tmp.get(0));
						}
					} catch (IOException e) {
						e.printStackTrace();
					}

					if (WSCommunicator.addTrip(from, to, userId, dateTxv.getText()
							.toString(), selectedDayList, timeTxv.getText()
							.toString(), driver
							.isChecked()) != -1) {
						Toast.makeText(getBaseContext(), "Trip saved",
								Toast.LENGTH_SHORT).show();
						goToTrips();
					} else
						Toast.makeText(getBaseContext(), "Trip not saved",
								Toast.LENGTH_SHORT)
						.show();
				}
			}
		});
	}

	protected void updateDateDisplay() {
		for (String day : selectedDayList.keySet()) {
			selectedDayList.put(day, false);
		}
		dateTxv.setText(new StringBuilder().append(mMonth + 1).append("-")
				.append(mDay).append("-").append(mYear).append(" "));
		dayTxv.setText(null);
		dayTxv.setVisibility(TextView.INVISIBLE);
		dateTxv.setVisibility(TextView.VISIBLE);
	}

	protected void updateTimeDisplay() {
		timeTxv.setText(new StringBuilder().append(mHour).append(":").append(
				mMinute));
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
					mDay);
		case DAY_DIALOG_ID:
			Dialog dayChooserDialog = createDayDialog();
			return dayChooserDialog;
		case TIME_DIALOG_ID:
			Dialog timeChooserDialog = new TimePickerDialog(this,
					mTimeSetListener, mHour, mMinute, true);
			return timeChooserDialog;
		case ADDRESS_DEPARTURE_DIALOG_ID:
			Dialog addressDepartureDialog = createAddressDialog(addressDepartureResult);
			return addressDepartureDialog;
		case ADDRESS_ARRIVAL_DIALOG_ID:
			Dialog addressArrivalDialog = createAddressDialog(addressArrivalResult);
			return addressArrivalDialog;
		}
		return null;
	}

	private Dialog createAddressDialog(
			final List<HelloRoadAddress> addressProposal) {
		final Dialog addressDialog = new Dialog(this);
		addressDialog.setTitle("Did you mean?");
		ListView listAddress = new ListView(this);

		ArrayAdapter<HelloRoadAddress> adapter = new ArrayAdapter<HelloRoadAddress>(
				this, android.R.layout.simple_list_item_1, addressProposal);
		listAddress.setAdapter(adapter);
		OnItemClickListener listener = new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				coord = addressProposal.get((int) id);
				if (departProposal == true)
					departure.setText(coord.toString());
				else
					arrival.setText(coord.toString());
				departProposal = false;
				addressDialog.dismiss();
			}

		};
		listAddress.setOnItemClickListener(listener);
		addressDialog.setContentView(listAddress);
		return addressDialog;
	}

	protected void goToTripList() {
		Intent i = new Intent(this, TripListView.class);
		startActivityForResult(i, ACTIVITY_CREATE);
	}

	protected Dialog createDayDialog() {
		Dialog dayChooserDialog = new Dialog(this);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, dayList);
		ListView dayListView = new ListView(this);
		dayListView.setAdapter(adapter);
		OnItemClickListener listener = new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				String day = ((TextView) view).getText().toString();
				if (selectedDayList.get(day) == false)
					selectedDayList.put(day, true);
				else
					selectedDayList.put(day, false);
				updateDayDisplay();
			}
		};
		dayListView.setOnItemClickListener(listener);
		dayChooserDialog.setContentView(dayListView);
		dayChooserDialog.setTitle("Day Frequency");
		return dayChooserDialog;
	}

	protected void updateDayDisplay() {
		StringBuilder str = new StringBuilder();
		for (String day : selectedDayList.keySet()) {
			if (selectedDayList.get(day) == true)
				str.append(day + ", ");
		}
		dayTxv.setText(str);
		dayTxv.setVisibility(TextView.VISIBLE);
		dateTxv.setText(null);
		dateTxv.setVisibility(TextView.INVISIBLE);
	}

	private void goToTrips() {
		Intent i = new Intent(this, TripListView.class);
		i.putExtra("userId", userId);
		startActivityForResult(i, ACTIVITY_CREATE);

	}

}
